const handleBlogRoute = require('./src/route/blog')
const handleUserRoute = require('./src/route/user')
const querystring = require('querystring')
const serverHandle = (req,res) => {
    res.setHeader('Content-type','application/json')
    //解析path
    const url = req.url
    req.path =url.split('?')[0]
    //解析query
    req.query = querystring.parse(url.split('?')[1])
    console.log(req.query)

    // 解析 cookie
    req.cookie = {};
    const cookieStr = req.headers.cookie || '';
    cookieStr.split(';').forEach(item => {
        if (!item) {
        return;
        }
        const arr = item.split('=');
        const key = arr[0].trim();
        const val = arr[1].trim();
        req.cookie[key] = val;
    });
    console.log('req.cookie---',req.cookie)



    const blogData = handleBlogRoute(req,res)
    if(blogData){
        blogData.then(blogData => {
            res.end(
                JSON.stringify(blogData)
            )
        })
        return
    }
    const userData = handleUserRoute(req,res)
    if(userData){
        userData.then(userData => {
            res.end(
                JSON.stringify(userData)
            )
        })
        return
    }

    // 404 情況
    res.writeHead(404, {
        'Content-type': 'text/plain'
    });
    res.write('404 Not Found');
    res.end();

}
// const http = require('http')
// const querystring  =   require('querystring')

// const server = http.createServer((req,res) => {
//     // console.log('请求方式--',req.method)
//     // const url = req.url
//     // console.log('url---',url)
//     // //用于在查询字符串中分隔键值对的子字符串。默认值: '&'。
//     // //split切掉前面的url只获取？后面的数据
//     // req.query = querystring.parse(url.split('?')[1],null,null)
//     // console.log('query--',req.query)
//     // res.writeHead(200, {'Content-Type': 'text/html'})

//     // res.end(
//     //     //将查询得到的对象转化成字符串
//     //     JSON.stringify(req.query)
//     // );
//     if(req.method === 'POST'){
//         console.log('content-type',req.headers['content-type'])
//         let postData = ''
//         req.on('data',chunk=>{
//             postData += chunk.toString()
//         })
//         req.on('end',()=>{
//             console.log('postData--',postData)
//             res.end(
//                 postData
//             )
//         })
//     }
// })


// server.listen(8083, ()=>{
//     console.log('Server is running at http://localhost:8083')
// })


module.exports = serverHandle